package com.petmall.cart.interceptor;

import com.qianji.common.constant.AuthConstant;
import com.qianji.common.constant.CartConstant;
import com.qianji.common.to.MemberResponseVo;
import com.qianji.common.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author liang zai
 * @date 2022/4/15 15:18
 * @description
 * 统一对登录的用户进行拦截，查看是登录的用户还是临时的用户
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    //只要线程不切换就一直有效
    public final static ThreadLocal<UserInfoTo> THREAD_LOCAL = new ThreadLocal<>();
    @Override
    //业务执行之前进行调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute!=null){
            //用户登录了
            userInfoTo.setUserId(attribute.getId());
        }
            //用户没有登录
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            //说明用户带了cookie
            for(Cookie cookie:cookies){
                String name = cookie.getName();
                String value = cookie.getValue();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    //说明用户已经存了user-key
                    userInfoTo.setUserKey(value);
                    userInfoTo.setTempUser(true);
                }
            }
        }
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            //如果没有cookie则分配一个
            String s = UUID.randomUUID().toString();
            userInfoTo.setUserKey(s);
        }
        //目标方法执行之前
        THREAD_LOCAL.set(userInfoTo);
        return true;
    }

    @Override
    //业务执行之后调用
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //命令浏览器保存一个cookie 一个月的时间
        UserInfoTo userInfoTo = THREAD_LOCAL.get();
        if (!userInfoTo.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            //设置域名的范围
            cookie.setDomain("petmall.com");
            //设置过期时间一个月   以秒为单位的
            cookie.setMaxAge(24*60*60*30);
            response.addCookie(cookie);
        }
    }
}
